import { useEffect } from "react";
import { Popconfirm, Pagination, Avatar, message, Row, Col } from "antd";
import { Button, ButtonGroup, Card as SemiCard, List } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete } from "@douyinfe/semi-icons";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import Jdenticon from "react-jdenticon";
import { AllBusinessRoleMembers, AllApplications, DeleteRoleMember } from "../_graphql/business_roles";
import SetRoleMembers from "../_modals/business_roles/set.members";

export default function ApplicationRolesPage() {
    const { windowInnerHeight, graphqlFetch } = useModel("global");
    const { kuboUrl } = useModel("kubo");
    const { setModalVisible, setModalTitle, setModalComponent, setModalStyle, setModalWidth } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        memberLoading: false,
        roleMembers: [],
        roleGroupMembers: [],
        applications: [],
        selectedApplication: {},
        roleLoading: false,
        roles: [],
        selectedRole: null,
        totalCount: 0,
        pageSize: 20,
        page: 1,
        orgRole: {}, //组织内查询出来的应用角色信息
    });

    const loadApplications = async () => {
        state.loading = true;
        state.roles = [];
        let res = await graphqlFetch({
            query: AllApplications,
            variables: {
                first: state.pageSize || 20,
                offset: (state.page - 1) * state.pageSize || 0,
            },
        });
        state.applications = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.selectedApplication = res?.a?.totalCount ? res.a.nodes[0] : {};
        state.loading = false;
    };

    useEffect(() => {
        loadApplications();
    }, []);

    const loadApplicatinRoles = async () => {
        state.roleLoading = true;
        state.selectedRole = null;
        state.roles = [];
        try {
            const { aiUuid, aiName, b } = state.selectedApplication;
            let data = { aiUuid, aiName };
            if (b?.nodes?.length) data = { ...data, ...b.nodes[0] };
            if (data.atHash) {
                let response = await fetch(kuboUrl + data.atHash + "/application_business_roles.json", {
                    cache: "no-cache",
                });
                let roles = await response.json();

                state.roles = roles || {};

                let keys = Object.keys(state.roles);
                keys.length > 0 && (state.selectedRole = keys[0]);
            }
        } catch (error) {}
        state.roleLoading = false;
    };

    useEffect(() => {
        state.selectedApplication?.aiUuid && loadApplicatinRoles();
    }, [state.selectedApplication?.aiUuid]);

    const loadRoleMembers = async () => {
        state.memberLoading = true;
        if (state.selectedApplication.aiUuid && state.selectedRole) {
            let res = await graphqlFetch({
                query: AllBusinessRoleMembers,
                variables: {
                    aiUuid: state.selectedApplication.aiUuid,
                    arName: state.selectedRole,
                },
            });
            state.roleMembers = res?.a?.nodes?.map((item) => ({ ...item, ...item.b })) || [];
        }
        state.memberLoading = false;
    };

    useEffect(() => {
        if (state.selectedApplication?.aiUuid && state.selectedRole) {
            loadRoleMembers();
        } else {
            state.roleMembers = [];
        }
    }, [state.selectedApplication, state.selectedRole]);

    const deleteRoleMember = async (omUuid) => {
        state.memberLoading = true;
        let res = await graphqlFetch({
            query: DeleteRoleMember,
            variables: {
                omUuid,
                aiUuid: state.selectedApplication.aiUuid,
                arName: state.selectedRole,
            },
        });
        if (res) message.success("移除成功");
        loadRoleMembers();
        state.memberLoading = false;
    };

    const openRoleSetMembers = () => {
        setModalTitle("设置应用角色成员");
        setModalStyle({ top: 100 });
        setModalWidth(700);
        setModalComponent(
            <SetRoleMembers
                application={state.selectedApplication}
                roleKey={state.selectedRole}
                role={state.roles[state.selectedRole]}
                reloadData={loadRoleMembers}
            />
        );
        setModalVisible(true);
    };

    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：53，卡面脚：56，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 48 - 53 - 4;

    return (
        <Row style={{ margin: 24 }} gutter={16}>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>应用列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplications()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight - 56 }}
                    footerStyle={{ padding: 0 }}
                    footerLine={true}
                    footer={
                        <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                            <div></div>
                            <Pagination
                                total={state.totalCount}
                                showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                                pageSize={state.pageSize}
                                current={state.page}
                                showSizeChanger={false}
                                onChange={(page) => (state.page = page)}
                            />
                        </div>
                    }
                >
                    <List
                        loading={state.loading}
                        dataSource={state.applications}
                        style={{ padding: 10, height: cardBodyHeight - 56, overflow: "auto" }}
                        renderItem={(item, index) => (
                            <List.Item
                                key={index}
                                className={`list-item ${state.selectedApplication?.aiUuid === item?.aiUuid ? "list-item-selected" : ""}`}
                                header={<Avatar shape="square" src={<Jdenticon value={item.aiName || "-"} />} />}
                                main={
                                    <div>
                                        <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.aiName || "-"}</div>
                                        {item?.aiDesc}
                                    </div>
                                }
                                onClick={() => (state.selectedApplication = item)}
                            ></List.Item>
                        )}
                    />
                </SemiCard>
            </Col>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>角色列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplicatinRoles()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                >
                    <List
                        loading={state.roleLoading}
                        dataSource={Object.keys(state.roles)}
                        renderItem={(key, index) => {
                            return (
                                <List.Item
                                    key={index}
                                    className={`list-item ${state.selectedRole === key ? "list-item-selected" : ""}`}
                                    header={<Avatar shape="square" src={<Jdenticon value={state.roles[key].label || "-"} />} />}
                                    main={
                                        <div>
                                            <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{state.roles[key]?.label + " " || " - "}</div>
                                            <div> {state.roles[key]?.text + " " || " - "}</div>
                                        </div>
                                    }
                                    onClick={() => (state.selectedRole = key)}
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>业务角色列表</span>}
                    headerExtraContent={
                        <ButtonGroup size={"default"} theme="borderless">
                            <Button icon={<IconPlusCircle />} disabled={!state.selectedRole} onClick={openRoleSetMembers}></Button>
                            <Button icon={<IconRefresh />} onClick={loadRoleMembers}></Button>
                        </ButtonGroup>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight - 10 }}
                >
                    <List
                        key="omUuid"
                        loading={state.memberLoading}
                        dataSource={state.roleMembers}
                        renderItem={(item, index) => {
                            return (
                                <List.Item
                                    key={index}
                                    className={`list-item`}
                                    header={<Avatar shape="square" src={<Jdenticon value={item?.omName || "-"} />} />}
                                    main={
                                        <div>
                                            <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.omName || "-"}</div>
                                        </div>
                                    }
                                    extra={
                                        <Popconfirm
                                            placement="topRight"
                                            title={`确认要从业务角色里移除该成员【${item?.omName}】吗?`}
                                            onConfirm={() => deleteRoleMember(item.omUuid)}
                                        >
                                            <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                                        </Popconfirm>
                                    }
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>
        </Row>
    );
}
